<?php

// Include config file
include_once('./common.php');

// Connect to database
$link = dbConnect();

//implant a shitton of threads
/*
for($i = 0; $i < 30000; $i++){
	$result = mysql_query("INSERT INTO mxp_threads (forumID, userID, topic, lastPost, lastUserID) VALUES (3, 1, 'Injection test ".$i."', ".time().", 1)");
}
header("Location: /mxp30/search.php");
exit;
*/

if (!isset($_POST['page']) || empty($_POST['page'])) {
    $page = 1;
}else{
	$page = mysql_real_escape_string($_POST['page']);
}

$threadsPerPage = mysql_real_escape_string($_POST['threadsPerPage']);

if(!isset($_POST['pagesToCache']) || $_POST['pagesToCache'] <= 0){
	$pagesToCache = 1;
}else{
	$pagesToCache = mysql_real_escape_string($_POST['pagesToCache']);
}

$offset = ($page - 1) * $threadsPerPage;

//search in BOOLEAN mode (allows, +, - "stuff in quotes"
if(isset($_POST['keywords']) && isset($_POST['author'])){
	$keywords = mysql_real_escape_string($_POST['keywords']);
	$author = mysql_real_escape_string($_POST['author']);

	$searchTopics = false;
	$searchPosts = false;
	
	//let's see if we have topics or posts
	if(isset($_POST['type']) && $_POST['type'] == "p"){
		$searchPosts = true;
	}else{
		$searchTopics = true;
	}
	
	//see what group the user belongs to
	$groups = array(mysql_real_escape_string($_POST['guestGroupID']));
	
	if(isset($_POST['flashUserID']) && $_POST['flashUserID'] > 0){
		$flashUserID = mysql_real_escape_string($_POST['flashUserID']);
		
		//search the forums they are allowed to as well as guest ones
		$result = mysql_query("SELECT gm.groupID FROM ".TABLE_PREFIX."_groupmembers gm WHERE gm.userID = $flashUserID");
		
		while($data = mysql_fetch_object($result)){
			//check to make sure that it's not the same as the guest ID
			if($data->groupID != $groups[0]){
				array_push($groups, $data->groupID);
			}
		}
	}
	
	//now we can query the threads
	$query = "SELECT SQL_CALC_FOUND_ROWS t.threadID, t.forumID, t.topic, t.lastPost, t.replies, t.views, t.userID, t.lastUserID
				FROM ".TABLE_PREFIX."_threads t,  
					 ".TABLE_PREFIX."_forums f";
	
	//if we are only searching posts, then add the posts to the request
	if($searchPosts){
		$query .= ", ".TABLE_PREFIX."_posts p";
	}
	
	//add an extra table request if we are searching by user
	if($author != ""){
		$query .= ", ".TABLE_PREFIX."_users u";
	}
					 
	//add the threads we are allowed to touch
	//$query .= " WHERE t.threadID IN (".implode(",", $threads).")";
	$query .= " WHERE f.groupID IN (".implode(",", $groups).")";
				
	//if we have to search specific forums
	if(isset($_POST['forumsToSearch']) && $_POST['forumsToSearch'] != ""){
		$query .= " AND f.forumID IN(".mysql_real_escape_string($_POST['forumsToSearch']).")";	
	}
	
	$query .= "AND t.forumID = f.forumID";
					 
	//check the keywords
	if($keywords != ""){
		if($_POST['type'] == "p"){
			$params = "p.message";
		}else{
			$params = "t.topic";
		}
		
		$query .= " AND MATCH(".$params.") AGAINST('".$keywords."' IN BOOLEAN MODE)";
	}
	
	//if author is in the mix
	if($author != ""){
		if($searchPosts){
			//look in every post
			$query .= " AND MATCH(u.username) AGAINST('".$author."' IN BOOLEAN MODE) AND p.userID = u.userID";
		}else{
			//otherwise just look at the author of topics
			$query .= " AND MATCH(u.username) AGAINST('".$author."' IN BOOLEAN MODE) AND t.userID = u.userID";
		}
	}
	
	//if we are looking in posts, make sure to get them all with the same topic
	if($searchPosts){
		$query .= " AND p.threadID = t.threadID";
	}
	
	//author of the thread and last poster
	//$query .= " AND u.userID = t.userID AND u2.userID = t.lastUserID";
	
	//finish off the query
	$query .= " GROUP BY t.threadID ORDER BY t.lastPost DESC LIMIT $offset,".($threadsPerPage*$pagesToCache);
	
	//setup the var for output
	$output = "output=success";
	
	//$output .= "&query=".$query; //output the query for debug purposes
	
	//echo $query;
	
	$result = mysql_query($query);
	$totalResult = mysql_query("SELECT FOUND_ROWS() AS totalResults");
	$dataTotal = mysql_fetch_object($totalResult);
	
	$threadsOnThisPage = mysql_num_rows($result);
	$totalThreadsFound = $dataTotal->totalResults;
	
	$output .= "&totalThreadsFound=".$totalThreadsFound;
	
	//get the total pages
	$totalPages = ceil($totalThreadsFound / $threadsPerPage);
	$output .= "&totalPages=$totalPages&currentPage=$page";
	
	//report back the keywords, author and post/thread selection
	/*
	$output .= "&keywords=".$_POST['keywords'];
	$output .= "&author=".$_POST['author'];
	$output .= "&searchTopics=".$searchTopics;
	$output .= "&searchPosts=".$searchPosts;
	*/
	
	//parse the data for flash
	$output .= "&totalResults=".$threadsOnThisPage;
	if($threadsOnThisPage > 0){
		$start = ($page - 1) * $threadsPerPage;
		for($i = $start; $i < $start + ($threadsPerPage * $pagesToCache); $i++){
			if($data = mysql_fetch_object($result)){			
				$output .= "&search" . $i . "threadID=" . $data->threadID;
				$output .= "&search" . $i . "topic=" . urlencode(stripslashes($data->topic));
				$output .= "&search" . $i . "author=" . urlencode(stripslashes(getUsername($data->userID)));
				$output .= "&search" . $i . "authorID=" . $data->userID;
				$output .= "&search" . $i . "lastPoster=" . urlencode(stripslashes(getUsername($data->lastUserID)));
				$output .= "&search" . $i . "lastPost=" . strftime("%m/%d/%y %I:%M %p", $data->lastPost);
				$output .= "&search" . $i . "views=" . $data->views;
				$output .= "&search" . $i . "replies=" . $data->replies;
				//$output .= "&search" . $i . "forumName=" . $data->forumName;
			}
		}
	}
	
	echo $output;
}

// Close link to database server
mysql_close($link);
?>